import {useUserStore} from "@/stores/modules/userStore"

import type {AxiosRequestConfig, Method} from "axios"
import axios from "axios"
import {error_code} from "./error-code"
import {getToken} from "./local"
import {ElMessage} from "element-plus";

const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 5000,
})
// 请求拦截器
instance.interceptors.request.use((config) => {
    if (getToken()) {
        config.headers.Token = getToken()
    }
    return config
})
// 必须先拦截一下
// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        return response.data
    },
    // 异常处理
    (err) => {
        const errMsg = error_code(err.response.status);
        if (errMsg) {
            ElMessage.error(errMsg)
            return Promise.reject(null)
        }
        return Promise.reject(new Error(err))
    },
)
type Data<T> = {
    code: number
    message: string
    data: T
}
const request = <T>(
    url: string,
    method: Method = "get",
    data?: object | string,
    config?: AxiosRequestConfig,
) => {
    return instance.request<T, Data<T>>({
        url,
        method,
        [method.toLowerCase() === "get" ? "params" : "data"]: data,
        ...config,
    })
}
export default request
